package com.acce.service.utils;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class RemoteUtils {

	public static String remote(String serviceAddr, String namesapce, String methodName, String requestMsg) throws Exception{
		String restr = null;
		EndpointReference targetEPR = new EndpointReference(serviceAddr);
		Options options = new Options();
		options.setAction("urn:" + methodName) ;
		options.setTo(targetEPR);
		ServiceClient sender = null;
		try {
			sender = new ServiceClient();
			sender.setOptions(options);
			OMFactory fac = OMAbstractFactory.getOMFactory();
			OMNamespace omNs = fac.createOMNamespace(namesapce, "");
			OMElement method = fac.createOMElement(methodName, omNs);
			OMElement name = fac.createOMElement("requestMsg", omNs);
			name.setText(requestMsg);
			method.addChild(name);
			method.build();
			OMElement response = sender.sendReceive(method);
//			System.out.println(response);
//			OMElement elementxx = response.getFirstElement();
//			System.out.println("xxxx:" + elementxx.getText());
//			OMElement element = response.getFirstChildWithName(new QName("accecard", "return"));
//			System.out.println(element.getText());
			OMElement element = response.getFirstElement();
			restr = element.getText();
		} catch (AxisFault e) {
			throw new Exception(e.getMessage());
		}finally{
			if(null != sender){
				try {
					sender.cleanupTransport();
				} catch (AxisFault e) {
					throw new Exception(e.getMessage());
				}
			}
		}
		return restr;
	}
}
